/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.piemenu.view;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import com.mogujie.tt.R;



public class PieMenu extends FrameLayout {

    private static final int MAX_LEVELS = 5;
    private static final long ANIMATION = 80;
   
    private boolean mIsLongClick;//长按监听使能
    private PathImage imageView;
    private LayoutParams lp =null;
    private boolean Fanmenushow = true; 
   
	public interface PieController {
		/**
		 * called before menu opens to customize menu returns if pie state has
		 * been changed
		 * 
		 * 之前菜单打开自定义菜单 返回如果派状态已经更改
		 */
		public boolean onOpen();

	}

    /**
     * A view like object that lives off of the pie menu
     * 一个视图像派菜单对象,生活
     */
	public interface PieView {

		public interface OnLayoutListener {
			public void onLayout(int ax, int ay, boolean left);
		}

		public void setLayoutListener(OnLayoutListener l);

		public void layout(int anchorX, int anchorY, boolean onleft,
                           float angle, int parentHeight);

		public void draw(Canvas c);

		public boolean onTouchEvent(MotionEvent evt);

	}

    private Point mCenter;
    private int mRadius;
    private int mRadiusInc;
    private int mSlop;
    private int mTouchOffset;
    private Path mPath;

    private boolean mOpen;
    private PieController mController;

    private List<PieItem> mItems;
    private int mLevels;
    private int[] mCounts;
    private PieView mPieView = null;

    // sub menus 子菜单
    private List<PieItem> mCurrentItems;
    private PieItem mOpenItem;//打开的条目菜单

    private Drawable mBackground;
    private Paint mNormalPaint;
    private Paint mSelectedPaint;
    private Paint mSubPaint;

    // touch handling 联系处理
    private PieItem mCurrentItem;//当前的条目

    private boolean mUseBackground;
    private boolean mAnimating;

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    public PieMenu(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
        initView();
        Log.v("PieMenu","The constructor------------1");
    }

    /**
     * @param context
     * @param attrs
     */
    public PieMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
        initView();
        Log.v("PieMenu","The constructor------------2");
    }

    /**
     * @param context
     */
    public PieMenu(Context context) {
        super(context);
        init(context);
        initView();
       
        Log.v("PieMenu","The constructor------------3");
    }

    private void init(Context ctx) {

		mItems = new ArrayList<PieItem>();// 扇形列表条目

		mLevels = 0;

		mCounts = new int[MAX_LEVELS];

		Resources res = ctx.getResources();
        //修改 mRadius mRadiusInc 可改弧度大小
		mRadius = (int) res.getDimension(R.dimen.qc_radius_start);// 90
		mRadiusInc = (int) res.getDimension(R.dimen.qc_radius_increment);// 105
		mSlop = (int) res.getDimension(R.dimen.qc_slop);// 10
		mTouchOffset = (int) res.getDimension(R.dimen.qc_touch_offset);// 20

		mOpen = false;

		setWillNotDraw(false);

		setDrawingCacheEnabled(false);

		mCenter = new Point(0, 0);// 中心点

		mBackground = res.getDrawable(R.drawable.qc_background_normal);// 从资源文件得到自定义扇形背景
		mNormalPaint = new Paint();// 画笔
		mNormalPaint.setColor(res.getColor(R.color.qc_normal));// 设置画笔颜色
		mNormalPaint.setAntiAlias(true);// 设置是否使用抗锯齿功能，会消耗较大资源，绘制图形速度会变慢。

		mSelectedPaint = new Paint();
		mSelectedPaint.setColor(res.getColor(R.color.qc_selected));
		mSelectedPaint.setAntiAlias(true);

		mSubPaint = new Paint();
		mSubPaint.setAntiAlias(true);
		mSubPaint.setColor(res.getColor(R.color.qc_sub));

    }

	/**
	 * 添加在帧布局的视图初始化
	 */
	private void initView() {
		if (imageView == null) {
			imageView = new PathImage(getContext());
			imageView.setShow(true);
			imageView.setImageResource(R.drawable.pie_menu);

			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
            //得到屏幕的宽度
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            int height = wm.getDefaultDisplay().getHeight();
            Log.v("PieMenu","width = "+width);
            Log.v("PieMenu","height = "+height);
			params.leftMargin = (int) (width - 70);// 先设置在中间
			params.topMargin = (int) (height/2 -14);
			lp = params;
			imageView.setLayoutParams(params);
			addView(imageView, params);

			imageView.setOnLongClickListener(new OnLongClickListener() {// 长按

						@Override
						public boolean onLongClick(View arg0) {
							// TODO Auto-generated method stub
							mIsLongClick = true;
							Log.v("", "mIsLongClick = " + mIsLongClick);
							return false;
						}
					});

			imageView.setOnClickListener(new OnClickListener() { // 点击

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub

							if (!mIsLongClick) {
								if (Fanmenushow)// 准备显示
								{
									setCenter(lp.leftMargin, lp.topMargin+30);//圆点
									show(Fanmenushow);
									Fanmenushow = false;

								} else {
									show(Fanmenushow);
									deselect();
									invalidate();
									Fanmenushow = true;

								}
							} else {
								mIsLongClick = false;
							}
						}
					});
		}
	}
    
	public void setController(PieController ctl) {
		mController = ctl;
	}

	public void setUseBackground(boolean useBackground) {
		mUseBackground = useBackground;
	}

    public void addItem(PieItem item) {//添加视图条目
        // add the item to the pie itself 将条目添加到扇形本身
        mItems.add(item);
        int l = item.getLevel();//得到 条形目的最大值
        mLevels = Math.max(mLevels, l);//最大值
        mCounts[l]++;
    }

    public void removeItem(PieItem item) {
        mItems.remove(item);
    }

    public void clearItems() {
        mItems.clear();
    }

    private boolean onTheLeft() {
        return mCenter.x < mSlop;
    }

    /**
     * guaranteed has center set
     * @param show
     */
    
    private void show(boolean show) {
		mOpen = show;
		if (mOpen) {
			// ensure clean state 清空状态
			mAnimating = false;
			mCurrentItem = null;// 当前选择的条目
			mOpenItem = null;// 打开的条目
			mPieView = null;

			mCurrentItems = mItems;// 赋值给予显示
			for (PieItem item : mCurrentItems) {

				item.setSelected(false);// 刷新出视图列表
			}
			if (mController != null) {
				boolean changed = mController.onOpen();
			}
			layoutPie();// 画出角度
			animateOpen();// 菜单刷出的动作
		}
		invalidate();// 重新绘画
    }
   
    
    private void animateOpen() {
        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
        anim.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {//更新
                for (PieItem item : mCurrentItems) {
                    item.setAnimationAngle((1 - animation.getAnimatedFraction()) * (- item.getStart()));
                }
                invalidate();
            }

        });
        anim.setDuration(2*ANIMATION);//运动的时间
        anim.start();
    }
    
   
    private void setCenter(int x, int y) {//设置扇形中心坐标
        if (x < mSlop) {
            mCenter.x = 0;
        } else {
            mCenter.x = getWidth();
        }
        mCenter.y = y;
    }

    private void layoutPie() { //扇形布局
        float emptyangle = (float) Math.PI / 16;//记录的圆周率
     
        int rgap = 2;
        int inner = mRadius + rgap;
        int outer = mRadius + mRadiusInc - rgap;
        int gap = 1;
        
        for (int i = 0; i < mLevels; i++) 
        {
            int level = i + 1;
            float sweep = (float) (Math.PI - 2 * emptyangle) / mCounts[level];
            
            float angle = emptyangle + sweep / 2;
            
            mPath = makeSlice(getDegrees(0) - gap, getDegrees(sweep) + gap, outer, inner, mCenter);//画出扇形区域
            
            for (PieItem item : mCurrentItems) 
            {
                if (item.getLevel() == level)
                {
                    View view = item.getView();
                    if (view != null) 
                    {
                        view.measure(view.getLayoutParams().width,
                                     view.getLayoutParams().height);//设置宽度 高度
                        
                        int w = view.getMeasuredWidth();
                        int h = view.getMeasuredHeight();
                     //   Log.v("","item.getView() w = "+w);
                     //   Log.v("","item.getView() h = "+h);
                        int r = inner + (outer - inner) * 2 / 3;
                        int x = (int) (r * Math.sin(angle));
                        int y = mCenter.y - (int) (r * Math.cos(angle)) - h / 2;
                        
                        if (onTheLeft()) 
                        {
                            x = mCenter.x + x - w / 2;
                        } 
                        else 
                        {
                            x = mCenter.x - x - w / 2;
                        }
                        view.layout(x, y, x + w, y + h);//左、上、右、下分别相距父视图的距离
                        
                    }
                    float itemstart = angle - sweep / 2;
                    item.setGeometry(itemstart, sweep, inner, outer);//设置窗口的x，y坐标，宽w、高h
                    angle += sweep;
                }
            }
            inner += mRadiusInc;
            outer += mRadiusInc;
        }
    }


    /**
     * converts a
     *
     * @param angle from 0..PI to Android degrees (clockwise starting at 3
     *        o'clock)
     * @return skia angle
     */
    private float getDegrees(double angle) {
        return (float) (270 - 180 * angle / Math.PI);//得到角度计算长度值
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mOpen) 
        {
      
            int state;
            if (mUseBackground) //没有执行
            {
                int w = mBackground.getIntrinsicWidth();
                int h = mBackground.getIntrinsicHeight();
                int left = mCenter.x - w;
                int top = mCenter.y - h / 2;
                mBackground.setBounds(left, top, left + w, top + h);//
                state = canvas.save();//保存画布状态
                if (onTheLeft()) 
                {
                    canvas.scale(-1, 1);
                }
                mBackground.draw(canvas);//把 mBackground 内容画到画布中  
                canvas.restoreToCount(state);//以返回到某个save状态之前
            }
            
            // draw base menu
            PieItem last = mCurrentItem;
         
            
            if (mOpenItem != null) 
            {
                last = mOpenItem;
            }
           
           // Log.v("","mCurrentItems ="+mCurrentItems);从这个路口进入
            
            for (PieItem item : mCurrentItems) 
            {
                if (item != last) 
                {
                    drawItem(canvas, item);
                }
            }
            
            
            if (last != null) 
            {
                drawItem(canvas, last);
            }
            
            
          
            if (mPieView != null)
            {
                mPieView.draw(canvas);
            }
            
            
        }
    }

    private void drawItem(Canvas canvas, PieItem item) {

		if (item.getView() != null) {
			Paint p = item.isSelected() ? mSelectedPaint : mNormalPaint;// 得到画笔

			if (!mItems.contains(item)) {

				p = item.isSelected() ? mSelectedPaint : mSubPaint;

			}

			int state = canvas.save();// 锁画布(为了保存之前的画布状态)
			if (onTheLeft()) {
				canvas.scale(-1, 1);
			}

			float r = getDegrees(item.getStartAngle()) - 270; // degrees(0)

			canvas.rotate(r, mCenter.x, mCenter.y);// 旋转多少度
			// 根据Path进行绘制扇形 画笔
			canvas.drawPath(mPath, p);
			canvas.restoreToCount(state);

			// draw the item view 画项目视图
			View view = item.getView();
			state = canvas.save();// 锁画布(为了保存之前的画布状态)
			canvas.translate(view.getX(), view.getY());// 把当前画布的原点移到(10,10),后面的操作都以(10,10)作为参照点，默认原点为(0,0)
			view.draw(canvas);// View组件的绘制
			canvas.restoreToCount(state);

		}

    }

    private Path makeSlice(float start, float end, int outer, int inner, Point center) {
		RectF bb = new RectF(center.x - outer, center.y - outer, center.x
				+ outer, center.y + outer);// 矩形
		RectF bbi = new RectF(center.x - inner, center.y - inner, center.x
				+ inner, center.y + inner);// 矩形

		Path path = new Path(); // 预先在View上将N个点连成一条"路径",然后调用Canvas的drawPath(path,paint)即可沿着路径绘制图形
		// 矩形中心 开始的度数 旋转多少度
		path.arcTo(bb, start, end - start, true);// 画一个弧线的路径

		path.arcTo(bbi, end, start - end);

		path.close();

		return path;
    }
    
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
		float x = ev.getX();
		float y = ev.getY();
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mIsLongClick = false;
			if (!Fanmenushow) {
				PointF polar = getPolar(x, y);
				PieItem item = findItem(polar);// 选择匹配项
				// Log.v("","item ="+item);
				if (item != null) {
					onEnter(item);
				}

				// Log.v("","mCurrentItem ="+mCurrentItem);
				if (mCurrentItem != null) {
					mCurrentItem.getView().performClick();// 选择目标打开是使用代码主动去调用控件的点击事件
					show(Fanmenushow);
					deselect();
					invalidate();
					Fanmenushow = true;
					return true;//，return true就不会传递过去了
				}

			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (Fanmenushow && mIsLongClick) {

				// Log.v("","ev.getX() = "+ev.getX());
				// Log.v("","ev.getY() = "+ev.getY());
				int dx = (int) ev.getX();
				int dy = (int) ev.getY();
				// Log.v("", "dx, dy " + dx + "," + dy);

				lp = (LayoutParams) imageView.getLayoutParams();
				lp.leftMargin = dx;
				lp.topMargin = dy;

				lp.leftMargin = lp.leftMargin - imageView.getWidth() / 2;
				lp.topMargin = lp.topMargin - imageView.getHeight() / 2;
				if (lp.topMargin < 0)
					lp.topMargin = 0;

				if (lp.topMargin >= getHeight() - imageView.getHeight())
					lp.topMargin = getHeight() - imageView.getHeight();

				if (lp.leftMargin < 0)
					lp.leftMargin = 0;

				if (lp.leftMargin >= getWidth() - imageView.getWidth())
					lp.leftMargin = getWidth() - imageView.getWidth();

				// Log.v("","lp.leftMargin = "+lp.leftMargin);
				// Log.v(""," lp.topMargin = "+ lp.topMargin);

				imageView.setLayoutParams(lp);

				return false;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (lp != null && mIsLongClick) {
				if (lp.leftMargin <= getWidth() / 2)
					lp.leftMargin = 0;
				else
					lp.leftMargin = getWidth() - imageView.getWidth();
				
				imageView.setLayoutParams(lp);
			}

			break;
		}

		return super.dispatchTouchEvent(ev);
    }
    
    
    // touch handling for pie 功能键
   /*
    @Override
    public boolean onTouchEvent(MotionEvent evt) {
        float x = evt.getX();
        float y = evt.getY();
        int action = evt.getActionMasked();//移动的动作
        if (MotionEvent.ACTION_DOWN == action) 
        {
        	
        	
        	
            if ((x > getWidth() - mSlop) || (x < mSlop))
            {
             
            	setCenter((int) x, (int) y);//设置扇形中心坐标
            //	Log.v("","x, y "+(int) x+","+(int) y);
                show(true);//画出菜单
                return true;
            }
        }
        else if (MotionEvent.ACTION_UP == action) 
        {
        	
         if (mOpen)
         {
                boolean handled = false;
                
                Log.v("","mPieView ="+mPieView);
                if (mPieView != null) 
                {
                    handled = mPieView.onTouchEvent(evt);
                }
                PieItem item = mCurrentItem;
                Log.v("","mAnimating ="+mAnimating);
                if (!mAnimating) 
                {
                    deselect();//能够及时刷新
                }
                show(false);//不显示
                if (!handled && (item != null) && (item.getView() != null)) //没有选择就为null
                {
                	Log.v("","mOpenItem mAnimating ="+mOpenItem +" "+mAnimating);
                    if ((item == mOpenItem) || !mAnimating) 
                    {
                    	Log.v("","performClick----------------");
                        item.getView().performClick();//选择目标打开是使用代码主动去调用控件的点击事件
                    }
                }
                return true;
           }
        }
        else if (MotionEvent.ACTION_CANCEL == action) //你的手指在屏幕上拖动一个listView或者一个ScrollView而不是去按上面的按钮时会触发这个事件 超过范围就会触发此事件
        {
        	Log.v("","MotionEvent.ACTION_CANCEL--------------");
            if (mOpen) {
                show(false);
            }
            if (!mAnimating) {
                deselect();
                invalidate();
            }
            return false;
        } 
        else if (MotionEvent.ACTION_MOVE == action) 
        {

            if (mAnimating) return false;
            boolean handled = false;
            PointF polar = getPolar(x, y);
            
            int maxr = mRadius + mLevels * mRadiusInc + 50;
            
            if (mPieView != null)
            {
                handled = mPieView.onTouchEvent(evt);
            }
            
            if (handled) 
            {
                invalidate();
                return false;
            }
            
            if (polar.y < mRadius) //移动不超多范围
            {
            //	Log.v("","mRadius , mOpenItem  ,mAnimating  ="+mRadius+" "+mOpenItem+" "+mAnimating);
            	
                if (mOpenItem != null) 
                {
                    closeSub();//关闭子菜单
                } 
                else if (!mAnimating)
                {
                    deselect();
                    invalidate();
                }
                return false;
            }
            
            if (polar.y > maxr) //移动超过范围
            {
            	Log.v("","maxr ="+maxr);
                deselect();
                show(false);
                evt.setAction(MotionEvent.ACTION_DOWN);
                if (getParent() != null) {
                    ((ViewGroup) getParent()).dispatchTouchEvent(evt);
                }
                return false;
            }
            
            PieItem item = findItem(polar);//选择匹配项
            if (item == null)//为null就不做任何操作 
            {
            
            }
            else if (mCurrentItem != item) //选中的不是当前的项 就
            {
                Log.v("","onEnter(item)--------------1");
            	onEnter(item);
                if ((item != null) && item.isPieView() && (item.getView() != null))
                {
                	 Log.v("","onEnter(item)--------------2");
                    int cx = item.getView().getLeft() + (onTheLeft()
                            ? item.getView().getWidth() : 0);
                    int cy = item.getView().getTop();
                    
                    mPieView = item.getPieView();
                    
                    layoutPieView(mPieView, cx, cy,
                            (item.getStartAngle() + item.getSweep()) / 2);
                      
                }
                invalidate();
            }
        }
        // always re-dispatch event
        return false;
    }*/

    private void layoutPieView(PieView pv, int x, int y, float angle) {
        pv.layout(x, y, onTheLeft(), angle, getHeight());//设置位置
    }

    /**
     * enter a slice for a view
     * updates model only
     * @param item
     */
    private void onEnter(PieItem item) {
        // deselect 
        if (mCurrentItem != null) {
            mCurrentItem.setSelected(false);
        }
      //  Log.v("","item ="+item);
        if (item != null) 
        {
            // clear up stack 清理堆栈
            playSoundEffect(SoundEffectConstants.CLICK);
            item.setSelected(true);//及时刷新
            mPieView = null;
            mCurrentItem = item;//当前条目赋值
          //  Log.v("","mOpenItem , mCurrentItem ="+mOpenItem+" "+mCurrentItem);
          //    Log.v("","mCurrentItem.hasItems() ="+mCurrentItem.hasItems());
            if ((mCurrentItem != mOpenItem) && mCurrentItem.hasItems()) 
            {
            	
                openSub(mCurrentItem);
                mOpenItem = item;//打开条目
            }
            
        }
        else 
        {
            mCurrentItem = null;
        }
      
    }

    private void animateOut(final PieItem fixed, AnimatorListener listener) {
        if ((mCurrentItems == null) || (fixed == null)) return;
        final float target = fixed.getStartAngle();
        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
        anim.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                for (PieItem item : mCurrentItems) {
                    if (item != fixed) {
                        item.setAnimationAngle(animation.getAnimatedFraction()
                                * (target - item.getStart()));
                    }
                }
                invalidate();
            }
        });
        anim.setDuration(ANIMATION);
        anim.addListener(listener);
        anim.start();
    }

    private void animateIn(final PieItem fixed, AnimatorListener listener) {
        if ((mCurrentItems == null) || (fixed == null)) return;
        final float target = fixed.getStartAngle();
        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
        anim.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                for (PieItem item : mCurrentItems) {
                    if (item != fixed) {
                        item.setAnimationAngle((1 - animation.getAnimatedFraction())
                                * (target - item.getStart()));
                    }
                }
                invalidate();

            }

        });
        anim.setDuration(ANIMATION);
        anim.addListener(listener);
        anim.start();
    }

    private void openSub(final PieItem item) {//打开子菜单
        mAnimating = true;//确认做此动作
        animateOut(item, new AnimatorListenerAdapter() 
        {
            public void onAnimationEnd(Animator a)//动作结束
            {
                for (PieItem item : mCurrentItems) 
                {
                    item.setAnimationAngle(0);
                }
                
                mCurrentItems = new ArrayList<PieItem>(mItems.size());
                int i = 0, j = 0;
                
                while (i < mItems.size()) 
                {
                    if (mItems.get(i) == item) 
                    {
                        mCurrentItems.add(item);
                    } 
                    else
                    {
                        mCurrentItems.add(item.getItems().get(j++));
                    }
                    i++;
                }
                layoutPie();
                animateIn(item, new AnimatorListenerAdapter() 
                {
                    public void onAnimationEnd(Animator a) 
                    {
                        for (PieItem item : mCurrentItems)
                        {
                            item.setAnimationAngle(0);
                        }
                        mAnimating = false;
                    }
                });
            }
        });
    }

    private void closeSub() {//关闭子菜单
        mAnimating = true;
        if (mCurrentItem != null) {
            mCurrentItem.setSelected(false);
        }
        animateOut(mOpenItem, new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator a) {
                for (PieItem item : mCurrentItems) {
                    item.setAnimationAngle(0);
                }
                mCurrentItems = mItems;
                mPieView = null;
                animateIn(mOpenItem, new AnimatorListenerAdapter() {
                    public void onAnimationEnd(Animator a) {
                        for (PieItem item : mCurrentItems) {
                            item.setAnimationAngle(0);
                        }
                        mAnimating = false;
                        mOpenItem = null;
                        mCurrentItem = null;
                    }
                });
            }
        });
    }

    private void deselect() {
        if (mCurrentItem != null)
        {
            mCurrentItem.setSelected(false);
        }
        if (mOpenItem != null)
        {
            mOpenItem = null;
            mCurrentItems = mItems;
        }
        mCurrentItem = null;
        mPieView = null;
    }

    private PointF getPolar(float x, float y) {
        PointF res = new PointF();//浮点坐标
        // get angle and radius from x/y 从x / y得到角度和半径
        res.x = (float) Math.PI / 2;
      
        x = mCenter.x - x;
        if (mCenter.x < mSlop) 
        {
            x = -x;
        }
        y = mCenter.y - y;
        
        res.y = (float) Math.sqrt(x * x + y * y);
        
        if (y > 0) 
        {
            res.x = (float) Math.asin(x / res.y);
        } 
        else if (y < 0) 
        {
            res.x = (float) (Math.PI - Math.asin(x / res.y ));
        }
        return res;
    }

    /**
     *
     * @param polar x: angle, y: dist
     * @return the item at angle/dist or null
     */
    private PieItem findItem(PointF polar) {
        // find the matching item: 找到匹配项:
        for (PieItem item : mCurrentItems) {
        	
            if (inside(polar, mTouchOffset, item)) 
            {
            //	Log.v("","item ="+item);
                return item;
            }
        }
        return null;
    }

    private boolean inside(PointF polar, float offset, PieItem item) {
        return (item.getInnerRadius() - offset < polar.y)
        && (item.getOuterRadius() - offset > polar.y)
        && (item.getStartAngle() < polar.x)
        && (item.getStartAngle() + item.getSweep() > polar.x);
    }
    
    class PathImage extends ImageView {//移动图标

        private boolean showBtn;


        public PathImage(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (showBtn) {
             canvas.drawCircle(getWidth() / 2, getHeight() / 2, getHeight() / 2, mNormalPaint);//画圆圈
              
            }
            super.onDraw(canvas);
        }

        public void setShow(boolean s) {
            showBtn = s;
        }

    }
   
}
